import { defineStore } from 'pinia'
import { store } from '../index'
import {
  setToken,
  getToken,
  removeToken,
  getCollapsible,
  setCollapsible,
  setPlatformKey,
  getPlatformKey,
  setUserInfo,
  getUserInfo
} from '@/utils/storage'
import { getSingleList } from '@/utils/index'
import { message } from 'ant-design-vue'
import { LoginParams, MenuRoutesMap, UserInfo } from '@/types/login'
import { cloneDeep } from 'lodash-es'
import { toEleTreeData } from '@/utils'
import md5 from 'js-md5'
import { encryptorPwd } from '@/utils/jsencrypt'
import api from '@/api'
import { json } from 'stream/consumers'
import { filterPlatformName } from '@/utils/constantMap'

const { login, logout, menuInquiry, sysAccountActionListInquiry, roleAuthList, getCurrentUser } = api

interface UserState {
  token: string
  selectActivePlatform: string | undefined
  userInfo: Partial<UserInfo>
  hasCachePermission: boolean
  routesMapList: MenuRoutesMap[]
  permissionActionList: string[]
  authList: any[]
  allAuthList: any[]
  collapsible: string
}

export const userStore = defineStore('user', {
  state: (): UserState => ({
    token: getToken() || '',
    hasCachePermission: false, // 是否已获取权限点
    routesMapList: [],
    selectActivePlatform: getPlatformKey(),
    permissionActionList: [],
    authList: [],
    allAuthList: [],
    userInfo: getUserInfo() || {},
    collapsible: getCollapsible() || '' // 折叠状态
  }),
  actions: {
    // 登录
    async login(LoginParams: LoginParams) {
      const loginData = cloneDeep(LoginParams)
      loginData.userPwd = encryptorPwd(loginData.userPwd as string)
      const res = await login(loginData)
      this.token = res.result?.token
      setToken(this.token)
    },
    // 退出登录
    async logout() {
      await logout()
      this.hasCachePermission = false
      this.resetToken()
    },
    // 获取用户信息
    async getUserInfo() {
      const res: any = await getCurrentUser()
      this.userInfo = res.result?.data || {}
      setUserInfo(this.userInfo)
    },
    // 选择平台
    async setSelectActivePlatform(value: string) {
      this.selectActivePlatform = value
      setPlatformKey(value)
    },
    // 获取菜单列表权限
    async getMenu() {
      const res: any = await menuInquiry()
      if (res.result && res.result.length) {
        let result = res.result
        let array: any[] = []
        let isActivePlatform = false
        if (result && result.length) {
          let filterName = ['home', 'statistics'] // 过滤一级菜单
          result.forEach((item: MenuRoutesMap) => {
            if (filterPlatformName.includes(item.functionUrl)) {
              if (item.childList && item.childList.length) {
                if (item.functionUrl === this.selectActivePlatform) {
                  isActivePlatform = true
                }

                item.childList.forEach((itemChild) => {
                  if (filterName.includes(itemChild.functionUrl)) {
                    itemChild.childList = [
                      {
                        authorityName: itemChild.authorityName,
                        functionUrl: itemChild.functionUrl + 'Info'
                      }
                    ]
                  }
                })
                array.push(item)
              }
            } else {
              array.push(item)
            }
          })
          if (array && array.length && !isActivePlatform) {
            this.selectActivePlatform = array[0].functionUrl
          }
        }
        this.routesMapList = array
      } else {
        message.error('权限功能不完整, 请重新配置')
        throw Error('权限功能不完整, 请重新配置')
      }
    },
    // 获取功能权限点列表
    async inquiryPermissionctionList() {
      const res: any = await sysAccountActionListInquiry()
      if (res.result && res.result.length) {
        this.permissionActionList = getSingleList(res.result, 'functionUrl')
        this.hasCachePermission = true
      } else {
        message.error('获取用户权限点失败, 请重新登录')
        throw Error('获取用户权限点失败, 请重新登录')
      }
    },
    // 获取角色权限
    async getRoleAuthList() {
      let res = await roleAuthList()
      let result = res.result
      let authList: any[] = []
      let allAuthList: any[] = []
      if (result && result.length) {
        result.forEach((item: any) => {
          if (item.appId === '0') {
            authList = toEleTreeData(item.authorityDetailList)
          }
          allAuthList.push({
            appId: item.appId,
            appName: item.appName,
            authorityDetailList: toEleTreeData(item.authorityDetailList)
          })
        })
      }
      this.authList = authList
      this.allAuthList = allAuthList
    },
    // 清除token
    resetToken() {
      this.token = ''
      removeToken()
    },
    // 菜单折叠状态
    setCollapsible() {
      this.collapsible = this.collapsible ? '' : 'true'
      setCollapsible(this.collapsible)
    }
  }
})

// 当pinia未初始化之前注入使用
// export const userStoreWithOut = () => {
//   return userStore(store)
// }
